package com.sys.platform.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.sys.platform.entity.*;
import com.sys.platform.entity.request.DossierDevice.DossierDeviceBatchAddDTO;
import com.sys.platform.entity.request.DossierDevice.DossierDeviceOpenOrCloseDTO;
import com.sys.platform.entity.vo.DossierDevice.DossierDeviceVO;
import com.sys.platform.mapper.*;
import com.sys.platform.service.IDossierDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 档案馆设备Service业务层处理
 *
 * @author yuanfuqiang
 * @date 2024-01-10
 */
@Slf4j
@Service
public class DossierDeviceServiceImpl implements IDossierDeviceService {

    @Autowired
    private DossierDeviceMapper dossierDeviceMapper;

    @Autowired
    private CameraMapper cameraMapper;

    @Autowired
    private DossierDevicePositionMapper dossierDevicePositionMapper;

    @Autowired
    private DossierDeviceWarningMapper dossierDeviceWarningMapper;

    @Autowired
    private AddressPlatformMapper addressPlatformMapper;


    /**
     * 查询档案馆设备列表
     *
     * @param dossierDevice 档案馆设备
     * @return 档案馆设备
     */
    @Override
    public List<DossierDeviceVO> selectDossierDeviceList(DossierDeviceVO dossierDevice) {
        List<DossierDeviceVO> dossierDeviceList = dossierDeviceMapper.selectDossierDeviceList(dossierDevice);
        List<DossierDeviceWarning> deviceWarningList = dossierDeviceWarningMapper.selectAll();
        dossierDeviceList.stream().forEach(item -> {
            Long count = deviceWarningList.stream().filter(warning -> warning.getDeviceId().equals(item.getDeviceId()) && warning.getType().equals(item.getType())).count();
            item.setWarningCount(Integer.valueOf(count.toString()));
        });
        return dossierDeviceList;
    }

    /**
     * 批量新增档案馆设备
     *
     * @param dto 档案馆设备
     * @return 结果
     */
    @Override
    public int batchInsertDossierDevice(DossierDeviceBatchAddDTO dto) {
        List<Camera> cameraList = cameraMapper.selectByCameraCodes(dto.getCameraCodeList());
        List<DossierDevice> dossierDeviceList = new ArrayList<>();
        cameraList.stream().forEach(camera -> {
            DossierDevice device = new DossierDevice();
            device.setIpAddress(camera.getIp());
            List<DossierDevice> list = dossierDeviceMapper.select(device);
            if (list.size() == 0) {
                device.setCameraName(camera.getCameraName());
                device.setContractStatus(Integer.parseInt(camera.getStatus()));
                device.setMainStream(camera.getMainStream());
                device.setStatus(Integer.parseInt(camera.getStatus()));
                device.setType(dto.getType());
                device.setRoomNum(dto.getRoomNum());
                device.setCreateTime(DateTime.now());
                dossierDeviceList.add(device);
            }
        });
        if (dossierDeviceList.size() <= 0) {
            throw new RuntimeException("设备已存在");
        }
        return dossierDeviceMapper.insertList(dossierDeviceList);
    }

    /**
     * 新增档案馆设备
     *
     * @param dossierDevice 档案馆设备
     * @return 结果
     */
    @Override
    public int insertDossierDevice(DossierDevice dossierDevice) {
        dossierDevice.setCreateTime(DateTime.now());
        return dossierDeviceMapper.insertSelective(dossierDevice);
    }

    /**
     * 修改档案馆设备
     *
     * @param dossierDevice 档案馆设备
     * @return 结果
     */
    @Override
    public int updateDossierDevice(DossierDevice dossierDevice) {
        dossierDevice.setUpdateTime(DateTime.now());
        return dossierDeviceMapper.updateByPrimaryKeySelective(dossierDevice);
    }

    /**
     * 批量删除档案馆设备
     *
     * @param ids 需要删除的档案馆设备主键
     * @return 结果
     */
    @Override
    public int deleteDossierDeviceByIds(Long[] ids) {
        AtomicInteger i = new AtomicInteger();
        Arrays.stream(ids).forEach(id -> {
            dossierDeviceMapper.deleteByPrimaryKey(id);
            //同步删除点位
            DossierDevicePosition dossierDevicePosition = new DossierDevicePosition();
            dossierDevicePosition.setDeviceId(id.toString());
            dossierDevicePositionMapper.delete(dossierDevicePosition);
            //同步删除告警
            DossierDevice dossierDevice = dossierDeviceMapper.selectByPrimaryKey(id);
            DossierDeviceWarning dossierDeviceWarning = new DossierDeviceWarning();
            dossierDeviceWarning.setDeviceId(dossierDevice.getDeviceId());
            dossierDeviceWarning.setType(dossierDevice.getType());
            dossierDeviceWarningMapper.delete(dossierDeviceWarning);
            i.set(1);
        });
        return i.get();
    }

    /**
     * 控制设备开关
     *
     * @param dto
     */
    @Override
    public boolean openOrClose(DossierDeviceOpenOrCloseDTO dto) {
        boolean falg = false;
        AddressPlatform addressPlatform = new AddressPlatform();
        addressPlatform.setId(5l);
        AddressPlatform platform = addressPlatformMapper.selectOne(addressPlatform);
        String url = platform.getIp() + ":" + platform.getPort() + "/open?opt=" + dto.getStatus() + "&id=" + dto.getId();
        log.info("控制设备开关url:{}", url);
        String str = HttpUtil.get(url);
        if (JSONObject.parseObject(str).getString("code").equals("200")) {
            if (dto.getStatus() == 0) { //关
                falg = false;
            } else { //开
                falg = true;
            }
        }
        return falg;
    }

}
